import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Card, Input, Modal, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { ModalStatus } from '@/utils/utils';
import ProductModal from '@/pages/product/ProductModal';
import Toolbar, { ToolbarItem } from '@/components/Toolbar';

const { Search } = Input;

const Product = props => {
  const {
    dataLoading,
    product: { data, keyword, pageInfo },
    dispatch,
  } = props;

  const [modalStatus, setModalStatus] = useState(ModalStatus.closed);
  const [currentRecord, setCurrentRecord] = useState(null);

  useEffect(() => {
    queryData();
  }, []);

  const columns = [
    { title: '名称', dataIndex: 'name' },
    { title: '价格', dataIndex: 'price' },
    {
      title: '操作',
      render: (_, record) => (
        <Button.Group size="small">
          <Button
            onClick={() => {
              setCurrentRecord(record);
              setModalStatus(ModalStatus.update);
            }}
          >
            编辑
          </Button>
          <Button type="danger" onClick={() => deleteProduct(record)}>
            删除
          </Button>
        </Button.Group>
      ),
    },
  ];

  const handlePageChange = ({ current, pageSize }) => {
    dispatch({
      type: 'product/syncPageInfo',
      pageInfo: {
        current,
        pageSize,
      },
    });
    queryData();
  };

  function deleteProduct(product) {
    const modal = Modal.confirm({
      title: '确认删除这条记录?',
      onOk: async () => {
        const success = await dispatch({
          type: 'product/DeleteProduct',
          id: product.id,
        });
        if (!success) {
          return;
        }
        queryData();
        modal.destroy();
      },
      onCancel: () => modal.destroy(),
      okText: '确定',
      cancelText: '取消',
    });
  }

  return (
    <PageHeaderWrapper>
      <Card>
        <Toolbar>
          <ToolbarItem>
            <Search
              value={keyword}
              onChange={e =>
                dispatch({
                  type: 'product/syncKeyword',
                  keyword: e.target.value,
                })
              }
              onSearch={() => {
                dispatch({
                  type: 'product/syncPageInfo',
                  pageInfo: {
                    current: 1,
                  },
                });
                queryData();
              }}
              enterButton
            />
          </ToolbarItem>
          <ToolbarItem>
            <Button onClick={() => setModalStatus(ModalStatus.add)}>添加</Button>
          </ToolbarItem>
        </Toolbar>
        <Table
          size="small"
          loading={dataLoading}
          columns={columns}
          dataSource={data}
          rowKey="id"
          pagination={{
            ...pageInfo,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showTotal(total, range) {
              return `${range[0]}-${range[1]}条 共 ${total} 条`;
            },
          }}
          onChange={handlePageChange}
        />
        <ProductModal
          status={modalStatus}
          currentRecord={currentRecord}
          onCancel={() => {
            setModalStatus(ModalStatus.closed);
            setCurrentRecord(null);
          }}
        />
      </Card>
    </PageHeaderWrapper>
  );

  function queryData() {
    dispatch({
      type: 'product/QueryProduct',
    });
  }
};

export default connect(({ product, loading }) => ({
  product,
  dataLoading: loading.effects['product/QueryProduct'],
}))(Product);
